package cn.com.cifi.mars.schedled;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.com.cifi.mars.bean.dto.GroupPriceRecordDto;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.OperatorTypeEnum;
import cn.com.cifi.mars.constant.TodoTypeCodeEnum;
import cn.com.cifi.mars.entity.SysJob;
import cn.com.cifi.mars.mapper.mars.PriceCoreDetailMapper;
import cn.com.cifi.mars.service.CommonService;
import cn.com.cifi.mars.service.IdmPositionGroupService;
import cn.com.cifi.mars.service.IdmPositionService;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.MonitoringConsoleService;
import cn.com.cifi.mars.service.OrgService;
import cn.com.cifi.mars.service.PriceVersionGroupService;
import cn.com.cifi.mars.service.SysJobService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.service.SysNoticeService;
import cn.com.cifi.mars.service.SysProjectFetchNumberService;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.StrUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SysTimingTask extends BaseAction {

	@Autowired
	private OrgService orgService;
	@Autowired
	private IdmUserService idmUserService;
	@Autowired
	private IdmPositionService idmPositionService;
	@Autowired
	private IdmPositionGroupService idmPositionGroupService;
	@Autowired
	private SysNoticeService sysNoticeService;
	@Autowired
	private SysJobService sysJobService;
	@Autowired
	private SysLogService sysLogService;
	@Autowired
	private MonitoringConsoleService monitoringConsoleService;
	@Autowired
	private SysProjectFetchNumberService sysProjectFetchNumberService;
	@Autowired
	private CommonService commonService;
	@Autowired
	private PriceCoreDetailMapper priceCoreDetailMapper;
	@Autowired
	private PriceVersionGroupService priceVersionGroupService;

	/**
	 * 同步组织机构
	 */
	@Scheduled(cron = "0 45 11,23 * * ?")
	public void createOrg() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_ONE);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					
					String timestamp = StrUtils.getTimeStamp2(25);
			    	List<String> orgdepids = orgService.getOrgdepidList();
			    	List<String> projectIds = orgService.incrementSyncIdmOrg("*",timestamp,"0",orgdepids,new ArrayList<>());
					//同步组织树
			    	orgService.addByStagesV2();
					//项目取数
	                 if(CollectionUtils.isNotEmpty(projectIds)) {
	                	 for(String projectId : projectIds) {
	     					sysProjectFetchNumberService.syncProjectFetchNumber(projectId,null);
	     				}
	                 }
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}

	/**
	 * 同步岗位数据
	 */
	@Scheduled(cron = "0 0 0,12 * * ?")
	public void createPosition() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_TWO);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					
					String time = StrUtils.getTimeStamp2(25);
					List<String> jobNums = idmPositionService.getJobNumList();
					idmPositionService.syncPosition(time, "0", "*",jobNums);
					
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}

	/**
	 * 同步岗位组数据
	 */
	@Scheduled(cron = "0 0 0,12 * * ?")
	public void createPositionGroup() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_THREE);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					// 时间戳
					String time = StrUtils.getTimeStamp2(25);
					List<String> groupIds = idmPositionGroupService.getJobDefinitionsIdList();
					idmPositionGroupService.syncPositionGroup(time, "0","*",groupIds);
					
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}

	/**
	 * 同步用户信息
	 * 注：IDM因东八区时区问题，在增量时间上需至少增加8个小时数据
	 */
	@Scheduled(cron = "0 0 0,12 * * ?")
	public void createUser() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_FOUR);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					// 时间戳
					String time = StrUtils.getTimeStamp2(25);
					idmUserService.syncUser(time, "0", "*");
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}

	/**
	 * 清洗组织机构层级任务
	 */
	@Scheduled(cron = "0 0 1,13 * * ?")
	public void creatByStagesV2() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_FIVE);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					orgService.addByStagesV2();
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}

	/**
	 * 同步nos系统签约数据 每天执行一次
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	public void createNos() {
		boolean appointIP = commonService.isAppointIP();
		if (!appointIP){
			return;
		}
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_SIX);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					sysNoticeService.syncNos();
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}

	/**
	 * 定时删除系统日志（保留一个月内日志即可）-每天执行一次
	 */
	@Scheduled(cron = "0 0 4 * * ?")
	public void deleteLog() {
		boolean appointIP = commonService.isAppointIP();
		if (!appointIP){
			return;
		}
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_FIFTEEN);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					sysLogService.deleteLog(Constants.THIRTY);
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}
	
	
	/**
	 * 每月前4天保存监控台预警提醒日志记录
	 */
    @Scheduled(cron = "0 30 5 * * ?")
	public void prepareWarningReminder() {
		// 截止年月
		String yearMonth = LocalDateTime.now().toLocalDate().toString().replace("-", "").substring(0, 6);
		// 验证是否是月底前4天
		boolean flag = StrUtils.isEndOfTheMonth();
		if (flag) {
			SysJob job = sysJobService.selectJobByCode(Constants.ZERO_EIGHTEEN_LOG);
			LocalDateTime start = null;
			LocalDateTime end = null;
			if (null != job) {
				Integer jobId = job.getId();
				int count = sysJobService.lockJobById(jobId);
				LocalDateTime lastUpdateTime = job.getUpdateTime();
				boolean isflag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
				if (count == 1 && !isflag) {
					try {
						start = LocalDateTime.now();
						monitoringConsoleService.warningReminderSave(yearMonth);
						end = LocalDateTime.now();
					} catch (Exception e) {
						log.error("context:" + e);
					} finally {
						sysJobService.resetJob(job, start, end);
					}
				}else {
					sysJobService.resetStatus(job);
				}
			}
		} 
	}

	/**
	 * 每月前4天发送监控台预警提醒到门户待办
	 */
    @Scheduled(cron = "0 45 8 * * ?")
	public void sendWarningReminder() {
		// 截止年月
		String yearMonth = LocalDateTime.now().toLocalDate().toString().replace("-", "").substring(0, 6);
		// 验证是否是月底前4天
		boolean flag = StrUtils.isEndOfTheMonth();
		if (flag) {
			SysJob job = sysJobService.selectJobByCode(Constants.ZERO_EIGHTEEN);
			LocalDateTime start = null;
			LocalDateTime end = null;
			if (null != job) {
				Integer jobId = job.getId();
				int count = sysJobService.lockJobById(jobId);
				LocalDateTime lastUpdateTime = job.getUpdateTime();
				boolean isflag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
				if (count == 1 && !isflag) {
					try {
						start = LocalDateTime.now();
						monitoringConsoleService.warningReminderSend(yearMonth,"");
						end = LocalDateTime.now();
					} catch (Exception e) {
						log.error("context:" + e);
					} finally {
						sysJobService.resetJob(job, start, end);
					}
				}else {
					sysJobService.resetStatus(job);
				}
			}
		} 
	}
	
	/**
	 * 消除所有预警提醒待办
	 * 每月1号的06点
	 */
	@Scheduled(cron = "0 0 6 * * ?")
	public void updateAllEliminateToDo() {
		//判断当前时间是不是1号
		LocalDate localDate=LocalDateTime.now().toLocalDate();
		int day=Integer.parseInt(localDate.toString().substring(8,10));
		if(day!=Constants.ONE) {
			return;
		}
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_TWENTY_FIVE);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean isflag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !isflag) {
				try {
					start = LocalDateTime.now();
					commonService.cleanTodo(TodoTypeCodeEnum.EARLY_WARNING.getKey(),OperatorTypeEnum.DELETE.getKey(),"","",null);
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}


	/**
	 * 定时检查货值代办补录
	 */
	@Scheduled(cron = "0 */30 * * * ?")
	public void noticeSupplementPortalTodo() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_TWENTY_SIXTEEN);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			if (count == 1) {
				try {
					start = LocalDateTime.now();
					sysNoticeService.noticeCheckSupplementPortalTodo();
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}
	
	
	/**
	 * 定时检查集团审批版
	 */
	@Scheduled(cron = "0 */10 * * * ?")
	@Transactional(rollbackFor=Exception.class)
	public void groupPrice() {
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_THIRTY_FIVE);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			if (count == 1) {
				try {
					start = LocalDateTime.now();
					
					List<GroupPriceRecordDto> list = priceCoreDetailMapper.selectGroupPriceRecord();
					if(CollectionUtils.isNotEmpty(list)) {
						for(GroupPriceRecordDto dto : list) {
							Integer id = dto.getId();
							String schemeId = dto.getSchemeId();
							String projectId = dto.getProjectId();
							//生产集团审批版数据
							priceVersionGroupService.createPriceVersionGroup(schemeId,projectId);
							
							priceCoreDetailMapper.updateGroupRefreshRecord(id);
						}
					}
					end = LocalDateTime.now();
				} catch (Exception e) {
					log.error("context:" + e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
	}
}
